import { AfterViewInit, Component, OnDestroy, OnInit } from '@angular/core';
import { WebGLService } from 'src/app/services/webgl.service';
import { Matrix4 } from 'src/app/util/matrix';

@Component({
    selector: 'rotated-matrix4',
    templateUrl: './rotated-matrix4.component.html',
    styleUrls: ['./rotated-matrix4.component.scss']
})
export class RotatedMatrix4Component implements OnInit, AfterViewInit, OnDestroy {
    // 顶点着色器
    private vertexShaderSource = `
        attribute vec4 a_Position;
        uniform mat4 u_xformMatrix;
        void main () {
            gl_Position = u_xformMatrix * a_Position;
        }  
    `;
    private fragShaderSource = `
        void main () {
            gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
        }
    `;

    private ANGLE: number = 0;
    private SCALE: number = 0.5;
    private scaleFlag: boolean = true;  // true 为放大， false 为缩小
    private gl: WebGLRenderingContext;
    private animationId: number;
    private u_xformMatrix: WebGLUniformLocation;

    constructor(private webglService: WebGLService) { }
    ngOnInit() { }
    ngAfterViewInit () {
        this.init();
    }
    ngOnDestroy () {
        this.animationId && window.cancelAnimationFrame(this.animationId);
    }

    private init () {
        const canvas = document.querySelector('#myCanvas') as HTMLCanvasElement;
        this.gl = canvas.getContext('webgl');

        // 初始化 shader
        this.webglService.initShader(this.gl, this.vertexShaderSource, this.fragShaderSource);

        // 初始化 VertexBuffer
        const n = this.initVertexBuffer(this.gl);

        const program = this.webglService.getProgramByGLContext(this.gl);
        // 可以将 u_xformMatrix 变量存储为属性
        this.u_xformMatrix = this.gl.getUniformLocation(program, 'u_xformMatrix');
        // 设置背景颜色
        this.gl.clearColor(0.0, 0.0, 0.0, 1.0);

        this.tick(this.gl, n);
    }

    private tick (gl: WebGLRenderingContext, n: number) {
        this.render(gl, n);
        this.animationId = window.requestAnimationFrame(() => { this.tick(gl, n)});
    }
    private render (gl: WebGLRenderingContext, n: number) {
        console.log('render');
        // 创建旋转矩阵, 注意 WebGL 中矩阵是列主序的，相当于变换矩阵的转置
        const { ANGLE, SCALE } = this;
        this.ANGLE++;

        if (this.scaleFlag) {
            this.SCALE += 0.005;
        } else {
            this.SCALE -= 0.005;
        }
        if (this.SCALE > 1.0 && this.scaleFlag) this.scaleFlag = false;
        else if (this.SCALE < 0.5 && !this.scaleFlag) this.scaleFlag = true;
        

        // 注意顺序，该变换是，先平移再旋转，最后缩放
        const xformMatrix = new Matrix4().setScale(SCALE, SCALE, 1).rotate(ANGLE, 0.0, 0.0, 1.0).translate(0.5, 0, 0);
        gl.uniformMatrix4fv(this.u_xformMatrix, false, xformMatrix.elements);

        gl.clear(gl.COLOR_BUFFER_BIT);

        // 画点
        gl.drawArrays(gl.TRIANGLES, 0, n);

    }

    private initVertexBuffer (gl: WebGLRenderingContext) {
        const vertices = new Float32Array([
            //x     y
            0.0,    0.5,
           -0.5,   -0.5,
            0.5,   -0.5
        ]);
        const n = 3;    // 点的个数
        const byteLen = vertices.BYTES_PER_ELEMENT;

        // 创建缓冲区对象
        const vertexBuffer = gl.createBuffer();
        
        // 将缓冲区对象绑定到目标
        gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);

        // 向缓冲区对象中写入数据
        gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

        const program = this.webglService.getProgramByGLContext(gl);
        const a_Position = gl.getAttribLocation(program, 'a_Position');

        // 将缓冲区对象分配给 a_Position 变量
        gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 2 * byteLen, 0);

        // 连接 a_Position 变量与分配给它的缓冲区对象
        gl.enableVertexAttribArray(a_Position);

        return n;
    }
}